package com.pig4cloud.pig.upload.controller;

import com.pig4cloud.pig.admin.api.entity.SysDictItem;
//import com.pig4cloud.pig.admin.api.feign.RemoteDictItemService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.upload.file.FileUtils;
import com.pig4cloud.pig.upload.util.FileUtil;
import com.pig4cloud.pig.upload.util.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.*;

/**
 * 文件上传,下载类
 */
@Slf4j
@Inner(value = false)
@RestController
@RequestMapping("/file")
public class FileUploadController {

//	@Resource
//	private RemoteDictItemService remoteDictItemService;

	@Value("${web.upload-path}")
	private String webContentPath;

	@Value("${web.img-url}")
	private String imgUrl;

	/**
	 * 文件上传
	 *
	 * @param upload_type 上传的图片 所属的功能模块 类型
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/upload/{uploadType}")
	@ResponseBody
	public R<Map<String, Object>> upload(@PathVariable("uploadType") Integer upload_type, HttpServletRequest request) {
//    	int upload_type = request.getParameter("type")!=null ? Integer.parseInt(request.getParameter("type")) :0;
		List<String> pictureUrls = new ArrayList<>();
		List<String> picturePaths = new ArrayList<>();
		List<String> pictureUrlsDelete = new ArrayList<>();
		boolean success = true;
		//可能会有多个文件同时上传
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		BufferedOutputStream stream = null;
		try {
			for (MultipartFile f : files) {
				if (f.isEmpty()) {
					continue;
				}
				String urlPrefix = "";
				R<SysDictItem> sysDictItem = null;//remoteDictItemService.info("upload_type", upload_type + "", SecurityConstants.FROM_IN);

				if (sysDictItem.getCode() == 0) {
					urlPrefix = sysDictItem.getData().getLabel();
				} else {
					urlPrefix = FileUtil.getUploadPrefix(upload_type);
				}
				String localDateMonth = DateUtils.getLocalDateMonth(LocalDate.now());
				urlPrefix = urlPrefix + "/" + localDateMonth + "/";
				byte[] b = f.getBytes();
				String paramName = f.getOriginalFilename();
				UUID uuid = UUID.randomUUID();
				String folderName = webContentPath + "/" + urlPrefix;
				File file = new File(folderName);
				if (!file.exists()) {
					file.mkdirs();
				}
				String url = urlPrefix + uuid.toString() + paramName.substring(paramName.lastIndexOf("."));
				stream = new BufferedOutputStream(new FileOutputStream(new File(webContentPath + "/" + url)));
				stream.write(b);
				stream.close();
				pictureUrls.add(url);
				picturePaths.add(imgUrl + url);
				pictureUrlsDelete.add(url);
				System.out.println(request.getRequestURL());
			}
		} catch (IOException e) {
			success = false;
			e.printStackTrace();
			//删除已经保存的图片
			for (String u : pictureUrlsDelete) {
				File file = new File(webContentPath + u);
				if (file.exists())
					file.delete();
			}
		}

		//可能会有多个文件同时上传
		Map<String, Object> map = new HashMap<>();
		map.put("file_name", pictureUrls);
		map.put("file_url", picturePaths);
		System.out.println("pictureUrls:" + pictureUrls);

		if (success) {
			return R.ok(map);
		} else {
			return R.failed("上传失败");
		}
	}


	/**
	 * APP 安装包文件上传
	 *
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/uploadApp/{platform}/{type}/{version}")
	@ResponseBody
	public R<Map<String, Object>> uploadApp(@PathVariable("platform") Integer platform,
											@PathVariable("type") Integer type,
											@PathVariable("version") String version, HttpServletRequest request) {
		List<String> pictureUrls = new ArrayList<>();
		List<String> picturePaths = new ArrayList<>();
		List<String> pictureUrlsDelete = new ArrayList<>();
		boolean success = true;
		//可能会有多个文件同时上传
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		BufferedOutputStream stream = null;
		try {
			for (MultipartFile f : files) {
				if (f.isEmpty()) {
					continue;
				}

				String fileName = FileUtil.getUploadPrefix(99);

				byte[] b = f.getBytes();
				String paramName = f.getOriginalFilename();
//				UUID uuid = UUID.randomUUID();
				String folderName = webContentPath + "/" + fileName;
				File file = new File(folderName);
				if (!file.exists()) {
					file.mkdir();
				}


				if (type == 1 || type == 3) {
					if (type == 1) {//  ios 安装包
						fileName += "ios/client/client.ipa";
					} else if (type == 3) {
						fileName += "ios/manager/manager.ipa";
					}
					boolean bl = FileUtils.deleteFile(webContentPath + "/" + fileName);
					if (bl) {
						System.out.println("文件已删除");
					}
				} else {
					if (type == 0) {//  Android 安装包
						fileName += "android/manager/";
					} else if (type == 2) {
						fileName += "android/client/";
					}
					fileName += "appversion_" + type + "_" + version + paramName.substring(paramName.lastIndexOf("."));
					boolean bl = FileUtils.deleteFile(webContentPath + "/" + fileName);
					if (bl) {
						System.out.println("文件已删除");
					}
				}

				if (platform == 0) {
					stream = new BufferedOutputStream(new FileOutputStream(new File(webContentPath + "/" + fileName)));
					stream.write(b);
					stream.close();
				} else {
					InputStream inputStream = f.getInputStream();
					if (inputStream != null) {
						OssUtil.upload(inputStream, fileName, 99);
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}

				pictureUrls.add(fileName);
				picturePaths.add(imgUrl + fileName);
				pictureUrlsDelete.add(fileName);
				System.out.println(request.getRequestURL());
			}
		} catch (IOException e) {
			success = false;
			e.printStackTrace();
			//删除已经保存的图片
			for (String u : pictureUrlsDelete) {
				File file = new File(webContentPath + "/" + u);
				if (file.exists())
					file.delete();
			}
		}

		//可能会有多个文件同时上传
		Map<String, Object> map = new HashMap<>();
		map.put("file_name", pictureUrls);
		map.put("file_url", picturePaths);
		System.out.println("pictureUrls:" + pictureUrls);

		if (success) {
			return R.ok(map);
		} else {
			return R.failed("上传失败");
		}
	}


	//文件下载
	@GetMapping("/download")
	public Object downloadFile(HttpServletRequest request, HttpServletResponse response) {
		String url = request.getParameter("url");
		if (url != null) {
			//设置文件路径
			File file = new File(webContentPath, url);
			if (file.exists()) {
				response.setContentType("application/octet-stream");
				response.setHeader("content-type", "application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;fileName=" + url);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("download " + url + " success");
					if (os != null) {
						os.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {

					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
}
